import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 一级路由
import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'
import Search from '@/views/search'
import Result from '@/views/result'
import Article from '@/views/article'
// 二级路由
import Home from '@/views/layout/home'
import User from '@/views/layout/user'
import Edit from '@/views/layout/user/edit'
import Chat from '@/views/layout/user/chat'
import Video from '@/views/layout/video'
import Wenda from '@/views/layout/wenda'

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: 'user',
        component: User
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'wenda',
        component: Wenda
      }
    ]
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/result',
    component: Result
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
const loginURL = ['/uesr', '/wenda', '/video', 'user/edit']
router.beforeEach(function(to, from, next) {
  console.log(from, to)
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    if (loginURL.some(ele => to.path === ele)) {
      // next('/login')
      // router.push('/login')
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
